package com.nattakute.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.nattakute.dao.TimeTableDAO;
import com.nattakute.model.Timetable;

@Repository
public class TimeTableDAOImpl implements TimeTableDAO{

	@Autowired
	private SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	
	public List<Timetable> getTimeTable() {
		// TODO Auto-generated method stub
		return sessionFactory.getCurrentSession().createQuery("from Timetable").list();
	}

	
	public Timetable getTimeTableById(Integer id) {
		Timetable timetable = null;
		try {
			timetable =(Timetable)sessionFactory.getCurrentSession().load(Timetable.class, id);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return timetable;
	}

	
	public Boolean addTimeTable(Timetable timeTable) {
		try {
			
			sessionFactory.getCurrentSession().save(timeTable);
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}

	
	public Boolean deleteTimeTable(Timetable timeTable) {
		try {
			sessionFactory.getCurrentSession().delete(timeTable);
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}

	
	public Boolean updateTimeTable(Timetable timeTable) {
		try {
			sessionFactory.getCurrentSession().update(timeTable);
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}

	@SuppressWarnings("unchecked")
	
	public List<Timetable> listTimeTableByClass(String classId) {
		List<Timetable> timetables=new ArrayList<Timetable>();
		Criteria timetableCriteria=sessionFactory.getCurrentSession().createCriteria(Timetable.class);
		timetableCriteria.add(Restrictions.eq("haslearn", false));
		Criteria classCriteria=timetableCriteria.createCriteria("classID");
		classCriteria.add(Restrictions.eq("classID", classId));
		try {
			timetables=timetableCriteria.list();
			return timetables;
		} catch (Exception e) {
			System.out.println("listTimeTableByClass fails");
			e.printStackTrace();
			return null;
		}
	}

	
	@SuppressWarnings("unchecked")
	public List<Timetable> showReport() {
		String sql = "select tt.startTime,tt.endTime,l.labName,c.className,re.instructor from request re,timetable tt,classes c,lab l where re.timeTableID = tt.timeTableID and tt.classID = c.classID and tt.labId = l.labID and re.statusID=1 and tt.hasLearn=1";
		SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(sql);
		query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
		return query.list();
	}

}
